<html lang="zh">

<head>
    <meta charset="utf-8" />
</head>

<body>
    <script>
        function authWindowOpen(url, origin, sendData) {

            return new Promise((resolve, reject) => {
                //获得窗口的垂直位置 
                var iHeight = window.screen.availHeight / 1.4;
                var iWidth = window.screen.availWidth / 1.4;
                var iTop = (window.screen.availHeight - 30 - iHeight) / 2;
                //获得窗口的水平位置 
                var iLeft = (window.screen.availWidth - 10 - iWidth) / 2;

                var popup = window.open(url, 'authWindow', 'height=' + iHeight + ',innerHeight=' + iHeight + ',width=' + iWidth + ',innerWidth=' + iWidth + ',top=' + iTop + ',left=' + iLeft + ',status=no,toolbar=no,menubar=no,location=no,resizable=no,scrollbars=0,titlebar=no');
                if (popup == null) {
                    reject("弹出窗口被禁止，请允许弹出窗口然后刷新页面")
                    return;
                }
                //探针
                var postFn = setInterval(function () {
                    popup.postMessage(sendData, origin);
                }, 100);

                window.onmessage = function (event) {
                    if (event.data.type === 'READY') {
                        clearInterval(postFn);
                    } else if (event.data.type === 'DATA') {
                        // { "type": "DATA", "data": { "token": "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiI2NyIsIlRPS0VOX1RZUEVfS0VZIjoiVVNFUiIsIlVTRVJfTE9HSU5fVFlQRV9LRVkiOjE3LCJUT0tFTl9ST0xFX0tFWSI6IlVTRVIiLCJleHAiOjE1OTE0MjkwNDQsImlhdCI6MTU4ODgzNzA0NH0.CNcWRy7dlN7jbI0D_EiDokv-wqRQpQ3CktxLhfJlnVojzeLSB2UQD3RfCkTVjeOnR424mCu2RwbEN7mUo1fbpw", "code": "IoygXY", "message": "成功" } }
                        resolve(event.data.data.code);
                    }
                }
            });
        }
        fetch("./config").then(r => r.json()).then(json => {
            authWindowOpen(json.url, "*", Object.assign({ grantType: "authorization_code", scope: "loginUser" }, json.option)).then(
                code => {
                    fetch("./code", {
                        body: code,
                        method: "POST"
                    }).then(res => res.text()).then(txt => window.location.href = txt);
                }
            )
            .catch(message => alert(message));
            //     authWindowOpen("http://58.16.67.132:8887/authorize", "*", {
            //     grantType: "authorization_code",
            //     platCode: "966ce1f36c0e4333ac4231fc644091b2",
            //     scope: "loginUser",
            //     state: "222"
            // })
        })
    </script>
</body>

</html>